package com.tcp1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
	private Socket socket;
	private Scanner scanner;
	public static void main(String[] args) {
		Client client = new Client();
		client.start();

	}
	public Client(){
		try {
			socket = new Socket("localhost", 8080);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void start(){
		try {

			ServerHandler handle = new ServerHandler();
			Thread t = new Thread(handle);
			t.setDaemon(true);
			t.start();

			//获取socket套接字的输出流
			OutputStream out = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, "utf-8");
			//通过现有的outputStream创建新的PrintWriter。此便捷构造方法创建必要的中间
			//OutputStreamWriter,后者使用默认字符编码将字符转换为字节
			PrintWriter pw = new PrintWriter(osw,true);
			scanner = new Scanner(System.in);
			while(true){
				pw.println(scanner.nextLine());
			}


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(socket!= null){
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	//执行服务端发送过来的数据并显示
	public class ServerHandler implements Runnable{

		@Override
		public void run() {
			try {
				//获取socket的输入流
				InputStream in = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(in, "utf-8");
				BufferedReader bf = new BufferedReader(isr);
				while(true){
					System.out.println(bf.readLine());
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

}
